﻿# -*- coding:utf-8 -*-
import datetime
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext, Context
from django.core.urlresolvers import reverse

from ktit.storage.forms import CategoryForm, PartForm, DocumentForm, DocumentReceiptForm, DocumentDeliveryForm, DocumentItemForm 
from ktit.storage.models import Category, Part, PartItem, Document, DocumentItem, DocumentReceipt, DocumentDelivery, Unit, Place
from ktit.storage.categories import create_cat_tree
from ktit.storage.contextprocessors import category_proc




@login_required
def document_open_list(request):
    documents = Document.objects.filter(state='N')  
    context = Context({
      'documents' : documents,
      'current_menu_item' : '3',
      'current_sub_menu_item':'1',
    })    
    return render_to_response('document_list.html', context, context_instance=RequestContext(request, processors=[category_proc]))

@login_required
def all(request):
    documents = Document.objects.select_related().all()  
    context = Context({
      'documents' : documents,
      'current_menu_item' : '3',
      'current_sub_menu_item':'2',
    })    
    return render_to_response('document_all.html', context, context_instance=RequestContext(request, processors=[category_proc]))



#select_

@login_required
def receipt_add_part(request, part_id):

    document = None
    documents = Document.objects.filter(state='N', kind='R')
    if len(documents) == 0:
        # создание документа
        document = Document(kind='R', name='Документ прихода', user=request.user, state='N')
        document.save()
        
    elif len(documents) > 1:
        # много документов - выбор
        pass  
  
    elif len(documents) == 1: 
        # один открытый документ - используем
        document = documents[0]
    
    part = get_object_or_404(Part, id = part_id)

    if request.method == 'POST':
        form = DocumentItemForm(document, part, request.POST)   
        if form.is_valid(): 
            docitem = form.save()
            
            #print docitem.quantity
            for i in xrange(docitem.quantity):
                partitem = PartItem(part=part, document_in=docitem, document_state='N')
                partitem.save()
            
               
            
            
            return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_property', args=[document.id])) 
    else:
        form = DocumentItemForm(document, part)




    context = Context({
      'form':form,
      'documents' : documents,
      'document': document,
      'part' : part,
    })
    return render_to_response('document_receipt_select_add_part.html', context, context_instance=RequestContext(request, processors=[category_proc]))




#delivery_add_part
def document_delivery_add_part(request, part_id):
    document = None
    documents = Document.objects.filter(state='N', kind='D')
    if len(documents) == 0:
        # создание документа
        document = Document(kind='D', name='Документ выдачи', user=request.user, state='N')
        document.save()
    elif len(documents) > 1:
        # много документов - выбор
        pass  
    elif len(documents) == 1: 
        # один открытый документ - используем
        document = documents[0]
    part = get_object_or_404(Part, id = part_id)

    if request.method == 'POST':
        form = DocumentItemForm(document, part, request.POST)   
        if form.is_valid(): 
            docitem = form.save()
            partitem = PartItem.objects.filter(part=part)
            for item in partitem[:docitem.quantity]:
                item.document_out=docitem
                item.document_state='N'
                item.save()
            return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_property', args=[document.id])) 
    else:
        form = DocumentItemForm(document, part)

    context = Context({
      'form':form,
      'documents' : documents,
      'document': document,
      'part' : part,
    })
    return render_to_response('document_delivery_add_part.html', context, context_instance=RequestContext(request, processors=[category_proc]))






#***************************************************
@login_required
def document_select_or_new(request, part_id, doc_kind, serial=None):
    part = get_object_or_404(Part, id = part_id)
    documents = Document.objects.filter(state='N', kind=doc_kind)
    if request.method == 'POST':
        form = DocumentForm(request.user, doc_kind, request.POST)
        if form.is_valid():
            newdoc = form.save()
            if doc_kind == 'R':
                return HttpResponseRedirect(reverse('ktit.storage.views.documents.receipt_add_part', args=[newdoc.id,part.id]))
            else:
                if serial:
                    return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_delivery_add_serial', args=[newdoc.id,part.id,serial]))
                else:
                    return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_delivery_add_part', args=[newdoc.id,part.id]))
    else:
        form = DocumentForm(request.user, doc_kind)        
    context = Context({
      'form':form,
      'documents' : documents,
      'part' : part,
      'doc_kind':doc_kind,
      'serial':serial,
    })
    return render_to_response('document_select_or_new.html', context, context_instance=RequestContext(request, processors=[category_proc]))



@login_required
def document_delivery_select_or_new(request, part_id):
    return document_select_or_new(request, part_id, 'D')



@login_required
def document_receipt_select_or_new(request, part_id):
    return document_select_or_new(request, part_id, 'R')



@login_required
def document_delivery_select_or_new_serial(request, part_id, serial):
    return document_select_or_new(request, part_id, 'D', serial)


#document_add_part
'''
@login_required
def receipt_add_part(request, doc_id, part_id):
    part = get_object_or_404(Part, id = part_id)
    document = get_object_or_404(Document, id = doc_id)
    if part.numbered=='Y':
        if request.method == 'POST':
            form = PartDocumentForm(part, document, request.POST)
            if form.is_valid():
                input_fields = request.POST.get('input_serial', '')
                if request.POST.has_key('input_serial'):
                    input_serial = [v for v in request.POST.getlist('input_serial') if v != '']
                else:
                    input_serial = []
                dociteminst0 = form.save(commit=False)
                dociteminst0.quantity = len(input_serial)
                dociteminst = form.save()
                for s in input_serial: 
                    doc_item_serial = PartDocumentSerial(docitem=dociteminst, serial=s)
                    doc_item_serial.save()

                return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_property', args=[doc_id]))
        else:
            form = PartDocumentForm(part, document) 
        context = Context({
          'form':form,
          'document' : document,
          'part' : part,
        })    
        return render_to_response('receipt_add_part_numbered_doc.html', context, context_instance=RequestContext(request, processors=[category_proc]))
    else:
        if request.method == 'POST':
            form = PartDocumentForm(part, document, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_property', args=[doc_id]))
        else:
            form = PartDocumentForm(part, document)  
        context = Context({
          'form' : form, 
          'document' : document,
          'part' : part,
        })    
        return render_to_response('receipt_add_part_doc.html', context, context_instance=RequestContext(request, processors=[category_proc]))
'''


#delivery_add_part
"""
def document_delivery_add_part(request, doc_id, part_id):



    document = None
    documents = Document.objects.filter(state='N', kind='R')
    if len(documents) == 0:
        # создание документа
        document = Document(kind='R', name='Документ прихода', user=request.user, state='N')
        document.save()
        
    elif len(documents) > 1:
        # много документов - выбор
        pass  
  
    elif len(documents) == 1: 
        # один открытый документ - используем
        document = documents[0]
    
    part = get_object_or_404(Part, id = part_id)
    
    
    

    
    part = get_object_or_404(Part, id = part_id)
    document = get_object_or_404(Document, id = doc_id)
    if part.numbered=='Y':
        if request.method == 'POST':
            form = PartDocumentForm(part, document, request.POST)
            if form.is_valid():
        
                if request.POST.has_key('serials'):
                    input_serial = [v for v in request.POST.getlist('serials') if v != '']
                
                    dociteminst0 = form.save(commit=False)
                    dociteminst0.quantity = len(input_serial)
                    dociteminst = form.save()
                
                    for serial in input_serial:
                        pds = PartDocumentSerial(docitem=dociteminst, serial=serial)
                        pds.save()
                        
                    return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_property', args=[doc_id])) 
            #print input_serial
                
        else:
            form = PartDocumentForm(part, document) 
            #serials = part.regnumberedpart_set.filter(out_doc=None)
        
        serials = PartDocumentSerial.objects.filter(docitem__part=part)
        
        context = Context({
          'document' : document,
          'part' : part,
          'serials':serials,
          'form':form,
        })    
        return render_to_response('document_delivery_add_part_numbered.html', context, context_instance=RequestContext(request, processors=[category_proc]))
    else:
        if request.method == 'POST':
            form = PartDocumentForm(part, document, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_property', args=[doc_id]))
        else:
            form = PartDocumentForm(part, document)  
        context = Context({
          'form' : form, 
          'document' : document,
          'part' : part,
        })    
        return render_to_response('document_delivery_add_part.html', context, context_instance=RequestContext(request, processors=[category_proc]))
    """



def document_delivery_add_serial(request, doc_id, part_id, serial):
    pass








@login_required
def document_property(request, doc_id):
#def open_document(request, doc_id):
    document = get_object_or_404(Document, id = doc_id)
    document_items = DocumentItem.objects.select_related().filter(document = doc_id)
    context = Context({
      'document' : document,
      'document_items':document_items,
    })    
    return render_to_response('document_property.html', context, context_instance=RequestContext(request, processors=[category_proc]))



@login_required
def document_edit(request, doc_id):
    document = get_object_or_404(Document, id = doc_id)
    if request.method == 'POST':
        form = DocumentForm(request.user, request.POST, instance=document)
        if form.is_valid():
            #print form.fields
            form.save()
            return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_open_list'))
    else:
        form = DocumentForm(request.user, instance=document)     
    context = Context({
      'form' : form,
    })    
    return render_to_response('form_document_edit.html', context, context_instance=RequestContext(request, processors=[category_proc]))
 

   
@login_required
def document_register(request, doc_id):
    """
    document = get_object_or_404(Document, id = doc_id)
    if document.kind == 'R':
        if request.method == 'POST':
            form = DocumentReceiptForm(document, request.POST)
            if form.is_valid():
                form.save()
                document.state='R'
                document.save()
                part_document = PartDocument.objects.select_related().filter(document = doc_id)
                for part in part_document:
                    part.part.quantity += part.quantity
                    part.part.save()    
                
                #for item in document_items:
                #    if item.part.numbered == 'Y':
                #        for serial in item.documentitemserial_set.all():
                #            rnp = RegNumberedPart(part=item.part, serial=serial, in_date=datetime.datetime.now(), in_doc=item.document, out_date=None, out_doc=None)
                #            rnp.save()
                #    else:
                #        rp = RegPart(part=item.part, date=datetime.datetime.now(), doc=item.document, doc_kind=item.document.kind, quantity=item.quantity)
                #        rp.save()
           
                return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_open_list'))
        else:
            form = DocumentReceiptForm(document)     
        context = Context({
          'form' : form,
        })    
        return render_to_response('form_document_register.html', context, context_instance=RequestContext(request, processors=[category_proc]))
    else:
        #DocumentDeliveryForm


        if request.method == 'POST':
            form = DocumentDeliveryForm(document, request.POST)
            if form.is_valid():
                form.save()
                document.state='R'
                document.save()
                part_document = PartDocument.objects.select_related().filter(document = doc_id)
                for part in part_document:
                    part.part.quantity -= part.quantity
                    part.part.save()    
          
                return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_open_list'))
        else:
            form = DocumentDeliveryForm(document)  
    """
    document = get_object_or_404(Document, id = doc_id)
    if request.method == 'POST':
        form = DocumentReceiptForm(document, request.POST)
        if form.is_valid():
            form.save()
            document.state='R'
            document.save()
            
            # ВЫБРАТЬ все DocumentItem's
            # и для всех связанных PartItem's document_state сделать ='R'
            
            for docitem in document.documentitem_set.all():
                
                docitem.rnp_indoc_set.update(document_state='R') 
                docitem.part.quantity=len(docitem.rnp_indoc_set.all())
                docitem.part.save()
            #
            return HttpResponseRedirect(reverse('ktit.storage.views.documents.document_open_list'))
            
    else:
        form = DocumentReceiptForm(document)  
   
    context = Context({
      'form' : form,
    })    
    return render_to_response('form_document_register.html', context, context_instance=RequestContext(request, processors=[category_proc]))




 